package com.mxpio.erp.inventory.provider;

import com.mxpio.erp.common.inventory.entity.Warehouse;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criterion;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import com.mxpioframework.security.access.datascope.provider.DataScapeContext;
import com.mxpioframework.security.access.datascope.provider.DataScapeProvider;
import com.mxpioframework.security.entity.Dept;
import com.mxpioframework.security.entity.UserDept;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : 吴盼盼
 * @Datetime : 2022/11/3 15:44
 * @Desc :
 * @Modor :  Modifytime:
 * @modDesc : 当前登录用户的仓库权限
 */
@Component
public class CurrentUserWareHouseProvider implements DataScapeProvider {
    @Override
    @Transactional(readOnly = true)
    public List<Criterion> provide(DataScapeContext context) {
        String loginUsername = SecurityUtils.getLoginUsername();//拿用户所属的部门和仓库信息中的所属部门来匹配
        List<Criterion> appendCriterions = new ArrayList<>();
        if (StringUtils.isBlank(loginUsername)){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));//如果未匹配到过滤条件，则增加一个不能正常匹配到数据的条件
            return appendCriterions;
        }
        List<UserDept> userDepts = JpaUtil.linq(UserDept.class).equal("userId", loginUsername).list();
        if (userDepts.size()==0){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));
            return appendCriterions;
        }
        UserDept userDept = userDepts.get(0);
        Dept dept = JpaUtil.getOne(Dept.class, userDept.getDeptId());
        if (dept==null){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));
            return appendCriterions;
        }
        List<Warehouse> warehouseList = JpaUtil.linq(Warehouse.class).equal("deptCode", dept.getDeptCode()).list();
        if (warehouseList.size()==0){
            appendCriterions.add(new SimpleCriterion("createTime", Operator.EQ,new Date(0)));
            return appendCriterions;
        }
        List<String> whcodes = warehouseList.stream().map(Warehouse::getWhCode).collect(Collectors.toList());
        appendCriterions.add(new SimpleCriterion("whCode", Operator.IN, whcodes));
        return appendCriterions;
    }
}
